package com.whynot.frame.wechat.http.http;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.whynot.frame.wechat.http.config.PropertiesUtils;
import com.whynot.frame.wechat.http.file.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.json.JSONObject;

public class HttpClientUtils{

	private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

	/**
	 * HttpClient的方式与微信交互的get/post方式
	 * @param requestUrl
	 * @param requestMethod
	 * @param outputStr
	 * @return
	 */
	public static JSONObject httpRequest(String requestUrl,
			String requestMethod, String outputStr) {
		HttpHost proxy = null;
		if(PropertiesUtils.getProperty("proxyMode").equals("yes")){
			new HttpHost(PropertiesUtils.getProperty("proxyIp"),Integer.parseInt(PropertiesUtils.getProperty("proxyPort")));
		}

		Request request = null;
		if("GET".equalsIgnoreCase(requestMethod)){
			StringBuffer buffer = new StringBuffer();
			buffer.append(requestUrl);
			if(StringUtils.isNotEmpty(outputStr)){
				buffer.append("&").append(outputStr);
			}
			request = Request.Get(buffer.toString());
		}else if("POST".equalsIgnoreCase(requestMethod)){
			if(StringUtils.isNotEmpty(outputStr)){
				request = Request.Post(requestUrl).bodyString(outputStr, ContentType.APPLICATION_JSON);
			}else{
				request = Request.Post(requestUrl);
			}
		}
		if(request == null){
			logger.error("无对应的请求");
		}
		StringBuffer bufferStr = new StringBuffer();
		try {
			if(proxy != null){
				request = request.viaProxy(proxy);
			}
			HttpResponse reponse = request.execute().returnResponse();
			HttpEntity entity = reponse.getEntity();
			bufferStr.append(EntityUtils.toString(entity, "UTF-8"));
		} catch (IOException e) {
			logger.error("获取响应失败:"+e.getMessage());
		}
		JSONObject obj = JSONObject.fromObject(bufferStr.toString());
		return obj;
	}

	/**
	 * 上传素材到微信
	 * @param requestUrl
	 * @param file
	 * @param content_type
	 * @return
	 */
	public static JSONObject uploadMediaFile(String requestUrl, File file,
			String content_type) {
		HttpHost proxy = null;
		if(PropertiesUtils.getProperty("proxyMode").equals("yes")){
			new HttpHost(PropertiesUtils.getProperty("proxyIp"),Integer.parseInt(PropertiesUtils.getProperty("proxyPort")));
		}
		Request request = Request.Post(requestUrl);
		if(request == null){
			logger.error("request请求失败");
		}
		String stn = null;
		try {
			if (file != null) {
			      HttpEntity entity = MultipartEntityBuilder
			            .create()
			            .addBinaryBody("media", file)
			            .setMode(HttpMultipartMode.RFC6532)
			            .build();
			      request.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.toString());
			      if(proxy != null){
					request = request.viaProxy(proxy);
				  }
			      request.body(entity);
			      stn= request.execute().returnContent().asString();
			}
		} catch (IOException e) {
			logger.error("上传临时素材失败:"+e.getMessage());
		}
		JSONObject obj = JSONObject.fromObject(stn);
		return obj;

	}

	/**
	 * 获取临时素材
	 * @param requestUrl
	 * @param requestMethod
	 * @param outputStr
	 * @return
	 */
	public static File downloadMediaFile(String requestUrl,
			String requestMethod, String outputStr) {
		HttpHost proxy = null;
		if(PropertiesUtils.getProperty("proxyMode").equals("yes")){
			new HttpHost(PropertiesUtils.getProperty("proxyIp"),Integer.parseInt(PropertiesUtils.getProperty("proxyPort")));
		}
		Request request = null;
		if("GET".equalsIgnoreCase(requestMethod)){
			StringBuffer buffer = new StringBuffer();
			buffer.append(requestUrl);
			if(StringUtils.isNotEmpty(outputStr)){
				buffer.append("&").append(outputStr);
			}
			request = Request.Get(buffer.toString());
		}
		if(request == null){
			logger.error("request请求失败");
		}
		try {
			if(proxy != null){
				request = request.viaProxy(proxy);
			}
			HttpResponse response = request.execute().returnResponse();
			HttpEntity entity = response.getEntity();
			 Header[] contentTypeHeader = response.getHeaders("Content-Type");
		      if (contentTypeHeader != null && contentTypeHeader.length > 0) {
		        if (ContentType.TEXT_PLAIN.getMimeType().equals(contentTypeHeader[0].getValue())) {
		          String responseContent = EntityUtils.toString(entity, "UTF-8");
		          JSONObject obj = JSONObject.fromObject(responseContent);
		          logger.error("获取临时素材失败:"+"错误码:"+obj.get("errcode")+"错误信息:"+obj.get("errmsg"));
		        }
		      }
		      InputStream inputStream = entity.getContent();
		      String fileName = getFileName(response);
		      if (StringUtils.isEmpty(fileName)) {
		        return null;
		      }
		      String[] name_ext = fileName.split("\\.");
		      File localFile = FileUtils.createTmpFile(inputStream, name_ext[0], name_ext[1]);
		      return localFile;

		    } catch (IOException e) {
		    	 logger.error("获取临时素材失败:"+e.getMessage());
			}
		return null;

	}

	/**
	 * 获取微信服务器响应头的文件类型
	 * @param response
	 * @return
	 */
	private static String getFileName(HttpResponse response) {
	    Header[] contentDispositionHeader = response.getHeaders("Content-disposition");
	    Pattern p = Pattern.compile(".*filename=\"(.*)\"");
	    Matcher m = p.matcher(contentDispositionHeader[0].getValue());
	    m.matches();
	    String fileName = m.group(1);
	    return fileName;
	}
}